<template>
  <el-input
    v-model="model"
    :formatter="(val: string) => val.replace(/[^\d]/, '')"
    :parser="(val: string) => val.replace(/[^\d]/, '')"
    type="text"
    :prefixIcon="prefixIcon"
    :maxlength="smsCodeLen"
    autocomplete="off"
    placeholder="请输入验证码"
    clearable
  >
    <template #append>
      <base-count-down-button ref="baseCountDownButtonRef" style="width: 120px" @click="send"></base-count-down-button>
    </template>
  </el-input>
</template>

<script setup lang="ts">
  import { inputProps } from 'element-plus';
  import type { PropType } from 'vue';
  const props = defineProps({
    ...inputProps,
    /** 验证码长度 */
    smsCodeLen: { type: Number, default: 6 },
    /** 绑定值 */
    modelValue: { type: String, default: '' },
    /** 是否显示发送失败的 Toast */
    showErrorToast: { type: String, default: '' },
    /** 发送验证码的接口函数 */
    senSmsCodeRequest: { type: Function as PropType<() => Promise<any>>, required: true },
  });
  const model = defineModel<string>('modelValue');
  const newValue = ref('');
  watchEffect(() => {
    newValue.value = props.modelValue;
  });
  const baseCountDownButtonRef: $RefComp<'BaseCountDownButton'> = ref(null);

  /**
   * 发送验证码
   */
  async function send() {
    try {
      baseCountDownButtonRef.value?.setLoadState(true);
      await props.senSmsCodeRequest();
      baseCountDownButtonRef.value?.setLoadState(false);
      baseCountDownButtonRef.value?.start(); // 开始倒计时
    } catch (err) {
      baseCountDownButtonRef.value?.setLoadState(false);
      props.showErrorToast && ElToast.error(err.msg || '验证码发送失败');
    }
  }
</script>
